<template>
  <div class="customer-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>客户管理</h2>
      <p class="page-description">管理客户信息，包括新增、编辑、删除和查看客户详情</p>
    </div>

    <!-- 调试信息 -->
    <div v-if="showDebugInfo" class="debug-info">
      <div class="debug-header">🔧 调试信息</div>
      <div>客户数据: {{ customerList.length }} 条</div>
      <div>API状态: {{ apiStatus }}</div>
      <div v-if="debugMessage">{{ debugMessage }}</div>
      <div v-if="lastError" class="error-message">❌ 最后错误: {{ lastError }}</div>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" @click="handleAdd" :icon="Plus">新增客户</el-button>
        <el-button @click="handleImport" :icon="Upload">导入</el-button>
        <el-button @click="toggleDebugInfo" type="info" size="small">
          {{ showDebugInfo ? '隐藏调试' : '显示调试' }}
        </el-button>
        <el-button @click="testApiConnection" type="success" size="small">
          测试API连接
        </el-button>
        <el-button @click="loadCustomerList" type="primary" size="small">
          重新加载
        </el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入客户名称或编号搜索"
          style="width: 300px"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch" :icon="Search"></el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 客户列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="customerList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="serialNumber" label="序号" width="80" />
        <el-table-column prop="customerNumber" label="客户编号" width="150" />
        <el-table-column prop="customerName" label="客户名称" width="200" />
        <el-table-column prop="companyName" label="公司名称" width="200" />
        <el-table-column prop="customerType" label="客户类型" width="120">
          <template #default="scope">
            <el-tag :type="getCustomerTypeTagType(scope.row.customerType)">
              {{ getCustomerTypeText(scope.row.customerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerStatus" label="客户状态" width="120">
          <template #default="scope">
            <el-tag :type="getCustomerStatusTagType(scope.row.customerStatus)">
              {{ getCustomerStatusText(scope.row.customerStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creditLimit" label="信用额度" width="120">
          <template #default="scope">
            {{ formatCurrency(scope.row.creditLimit) }}
          </template>
        </el-table-column>
        <el-table-column prop="creditRating" label="信用等级" width="120">
          <template #default="scope">
            <el-tag :type="getCreditRatingTagType(scope.row.creditRating)">
              {{ getCreditRatingText(scope.row.creditRating) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isEnabled ? 'success' : 'danger'">
              {{ scope.row.isEnabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="info" size="small" @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[4, 6, 8, 10]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <CustomerDialog
      v-model="dialogVisible"
      :customer="currentCustomer"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />

    <!-- 查看详情对话框 -->
    <CustomerDetailDialog
      v-model="detailDialogVisible"
      :customer="currentCustomer"
    />

    <!-- 导入对话框 -->
    <ImportDialog
      v-model="importVisible"
      @success="loadCustomerList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Search } from '@element-plus/icons-vue'
import CustomerDialog from './components/CustomerDialog.vue'
import CustomerDetailDialog from './components/CustomerDetailDialog.vue'
import { customerApi } from '@/api/customerApi'
import { resolveNamesByIds } from '@/api/referenceApi'
import { getErrorMessage } from '@/utils/error'
import type { Customer, CustomerDto, PaginationParams } from '@/types/customer'
import ImportDialog from './components/ImportDialog.vue'

// 响应式数据
const loading = ref(false)
const customerList = ref<CustomerDto[]>([])
const searchKeyword = ref('')
const showDebugInfo = ref(false)
const apiStatus = ref('未连接')
const debugMessage = ref('')
const lastError = ref('')

// 分页
const pagination = reactive<PaginationParams>({
  currentPage: 1,
  pageSize: 4,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const currentCustomer = ref<Customer | null>(null)
const importVisible = ref(false)

// 选中的行
const selectedRows = ref<CustomerDto[]>([])

// 计算属性
const serialNumber = computed(() => {
  return (pagination.currentPage - 1) * pagination.pageSize + 1
})

// 方法
const loadCustomerList = async () => {
  try {
    loading.value = true
    apiStatus.value = '连接中...'
    
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize
    }
    
    const response = await customerApi.getCustomerList(params as any)
    
    if (response.code === 200) {
      const pageData = (response.data as any).pageData || (response.data as any).data || []
      customerList.value = pageData.map((customer: any, index: number) => ({
        ...customer,
        // 兼容后端大写字段
        id: customer.id ?? customer.Id,
        customerNumber: customer.customerNumber ?? customer.CustomerNumber,
        customerName: customer.customerName ?? customer.CustomerName,
        companyName: customer.companyName ?? customer.CompanyName,
        customerType: customer.customerType ?? customer.CustomerType,
        customerStatus: customer.customerStatus ?? customer.CustomerStatus,
        creditLimit: Number(customer.creditLimit ?? customer.CreditLimit ?? 0),
        creditRating: customer.creditRating ?? customer.CreditRating,
        paymentTerms: customer.paymentTerms ?? customer.PaymentTerms ?? '',
        isEnabled: customer.isEnabled ?? customer.IsEnabled,
        createdAt: customer.createdAt ?? customer.CreatedAt,
        updatedAt: customer.updatedAt ?? customer.UpdatedAt,
        serialNumber: serialNumber.value + index
      }))
      pagination.total = (response.data as any).totalCount ?? (response.data as any).TotalCount ?? 0
      apiStatus.value = '连接成功'
      debugMessage.value = `成功加载 ${customerList.value.length} 条客户数据`
      lastError.value = ''
    } else {
      throw new Error(response.message || '获取客户列表失败')
    }
  } catch (error: unknown) {
    apiStatus.value = '连接失败'
    const msg = getErrorMessage(error)
    lastError.value = msg || '未知错误'
    ElMessage.error(`加载客户列表失败: ${msg}`)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadCustomerList()
}

const handleAdd = () => {
  currentCustomer.value = null
  dialogMode.value = 'add'
  dialogVisible.value = true
}

const handleEdit = async (row: CustomerDto) => {
  try {
    loading.value = true
    // 拉取后端详情，确保字段完整
    const res = await customerApi.getCustomerById(row.id as any)
    if (res.code === 200 && res.data) {
      const d: any = res.data
      // 规范化字段大小写与名称
      const normalized: any = {
        id: d.id ?? d.Id,
        customerNumber: d.customerNumber ?? d.CustomerNumber ?? '',
        customerName: d.customerName ?? d.CustomerName ?? '',
        companyName: d.companyName ?? d.CompanyName ?? '',
        customerType: d.customerType ?? d.CustomerType ?? '',
        customerStatus: d.customerStatus ?? d.CustomerStatus ?? '',
        partnerLevelId: d.partnerLevelId ?? d.customerLevelId ?? d.CustomerLevelId,
        partnerCategoryId: d.partnerCategoryId ?? d.customerCategoryId ?? d.CustomerCategoryId,
        salesRepresentativeId: d.salesRepresentativeId ?? d.SalesRepresentativeId,
        industryId: d.industryId ?? d.IndustryId,
        businessNatureId: d.businessNatureId ?? d.BusinessNatureId,
        locationId: d.locationId ?? d.LocationId,
        creditLimit: Number(d.creditLimit ?? d.CreditLimit ?? 0),
        creditRating: d.creditRating ?? d.CreditRating ?? '',
        paymentTerms: d.paymentTerms ?? d.PaymentTerms ?? '',
        unifiedSocialCreditCode: d.unifiedSocialCreditCode ?? d.UnifiedSocialCreditCode ?? '',
        phoneNumber: d.phoneNumber ?? d.Phone ?? d.Mobile ?? d.PhoneNumber ?? '',
        faxNumber: d.faxNumber ?? d.FaxNumber ?? '',
        email: d.email ?? d.Email ?? '',
        website: d.website ?? d.Website ?? '',
        companyAddress: d.companyAddress ?? d.CompanyAddress ?? '',
        remarks: d.remarks ?? d.Remarks ?? '',
        isEnabled: d.isEnabled ?? d.IsEnabled ?? true,
        createdAt: d.createdAt ?? d.CreatedAt ?? d.createTime ?? d.CreateTime ?? '',
        updatedAt: d.updatedAt ?? d.UpdatedAt ?? d.modifyTime ?? d.ModifyTime ?? ''
      }
      
      currentCustomer.value = normalized
  dialogMode.value = 'edit'
  dialogVisible.value = true
    } else {
      throw new Error(res.message || '获取客户详情失败')
    }
  } catch (error: unknown) {
    const msg = getErrorMessage(error)
    ElMessage.error(`获取客户详情失败: ${msg}`)
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row: CustomerDto) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户 "${row.customerName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const response = await customerApi.deleteCustomer(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadCustomerList()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error: unknown) {
    if (error !== 'cancel') {
      const msg = getErrorMessage(error)
      ElMessage.error(`删除失败: ${msg}`)
    }
  } finally {
    loading.value = false
  }
}

const handleView = async (row: CustomerDto) => {
  try {
    loading.value = true
    // 拉取后端详情，确保字段完整
    const res = await customerApi.getCustomerById(row.id as any)
    if (res.code === 200 && res.data) {
      const d: any = res.data
      // 规范化字段大小写与名称
      const normalized: any = {
        id: d.id ?? d.Id,
        customerNumber: d.customerNumber ?? d.CustomerNumber ?? '',
        customerName: d.customerName ?? d.CustomerName ?? '',
        companyName: d.companyName ?? d.CompanyName ?? '',
        customerType: d.customerType ?? d.CustomerType ?? '',
        customerStatus: d.customerStatus ?? d.CustomerStatus ?? '',
        partnerLevelId: d.partnerLevelId ?? d.customerLevelId ?? d.CustomerLevelId,
        partnerCategoryId: d.partnerCategoryId ?? d.customerCategoryId ?? d.CustomerCategoryId,
        salesRepresentativeId: d.salesRepresentativeId ?? d.SalesRepresentativeId,
        industryId: d.industryId ?? d.IndustryId,
        businessNatureId: d.businessNatureId ?? d.BusinessNatureId,
        locationId: d.locationId ?? d.LocationId,
        creditLimit: Number(d.creditLimit ?? d.CreditLimit ?? 0),
        creditRating: d.creditRating ?? d.CreditRating ?? '',
        paymentTerms: d.paymentTerms ?? d.PaymentTerms ?? '',
        unifiedSocialCreditCode: d.unifiedSocialCreditCode ?? d.UnifiedSocialCreditCode ?? '',
        phoneNumber: d.phoneNumber ?? d.Phone ?? d.Mobile ?? d.PhoneNumber ?? '',
        faxNumber: d.faxNumber ?? d.FaxNumber ?? '',
        email: d.email ?? d.Email ?? '',
        website: d.website ?? d.Website ?? '',
        companyAddress: d.companyAddress ?? d.CompanyAddress ?? '',
        remarks: d.remarks ?? d.Remarks ?? '',
        isEnabled: d.isEnabled ?? d.IsEnabled ?? true,
        // 同时提供 createdAt/updatedAt 以兼容详情组件展示
        createdAt: d.createdAt ?? d.CreatedAt ?? d.createTime ?? d.CreateTime ?? '',
        updatedAt: d.updatedAt ?? d.UpdatedAt ?? d.modifyTime ?? d.ModifyTime ?? ''
      }
      // 附加用于展示的名称字段
      normalized.customerLevelName = d.customerLevelName ?? d.CustomerLevelName
      normalized.customerCategoryName = d.customerCategoryName ?? d.CustomerCategoryName
      normalized.salesRepresentativeName = d.salesRepresentativeName ?? d.SalesRepresentativeName
      normalized.industryName = d.industryName ?? d.IndustryName
      normalized.businessNatureName = d.businessNatureName ?? d.BusinessNatureName
      normalized.locationName = d.locationName ?? d.LocationName

      // 如果名称缺失，调用参考数据接口补齐名称
      if (!normalized.customerLevelName || !normalized.customerCategoryName || !normalized.businessNatureName || !normalized.industryName || !normalized.locationName || !normalized.salesRepresentativeName) {
        const names = await resolveNamesByIds({
          levelId: normalized.partnerLevelId ?? undefined,
          categoryId: normalized.partnerCategoryId ?? undefined,
          natureId: normalized.businessNatureId ?? undefined,
          industryId: normalized.industryId ?? undefined,
          locationId: normalized.locationId ?? undefined,
          personId: normalized.salesRepresentativeId ?? undefined
        })
        Object.assign(normalized, names)
      }

      currentCustomer.value = normalized
      detailDialogVisible.value = true
    } else {
      throw new Error(res.message || '获取客户详情失败')
    }
  } catch (error: unknown) {
    const msg = getErrorMessage(error)
    ElMessage.error(`获取客户详情失败: ${msg}`)
  } finally {
    loading.value = false
  }
}

const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadCustomerList()
  ElMessage.success(dialogMode.value === 'add' ? '新增成功' : '更新成功')
}

const handleSelectionChange = (rows: CustomerDto[]) => {
  selectedRows.value = rows
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadCustomerList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadCustomerList()
}

const handleImport = () => {
  importVisible.value = true
}

const toggleDebugInfo = () => {
  showDebugInfo.value = !showDebugInfo.value
}

// const testApiConnection = async () => {
//   try {
//     apiStatus.value = '测试中...'
//     const response = await customerApi.getCustomerList({ PageIndex: 1, PageSize: 1 })
//     apiStatus.value = '连接正常'
//     debugMessage.value = 'API连接测试成功'
//     ElMessage.success('API连接正常')
//   } catch (error: unknown) {
//     apiStatus.value = '连接异常'
//     const msg = getErrorMessage(error)
//     debugMessage.value = `API连接测试失败: ${msg}`
//     ElMessage.error(`API连接异常: ${msg}`)
//   }
// }

// 工具方法
const getCustomerTypeText = (type: string | number) => {
  if (type === undefined || type === null || type === '') return '未设置'
  const map: Record<string, string> = { 'Individual': '个人', 'Enterprise': '企业', '1': '个人', '2': '企业' }
  return map[String(type)] || '未设置'
}

const getCustomerTypeTagType = (type: string | number) => {
  const map: Record<string, string | undefined> = { 'Individual': 'info', 'Enterprise': 'success', '1': 'info', '2': 'success' }
  return map[String(type)]
}

const getCustomerStatusText = (status: string | number) => {
  if (status === undefined || status === null || status === '') return '未设置'
  const map: Record<string, string> = { 'Active': '活跃', 'Inactive': '非活跃', 'Blacklisted': '黑名单', '1': '活跃', '2': '非活跃', '3': '黑名单' }
  return map[String(status)] || '未设置'
}

const getCustomerStatusTagType = (status: string | number) => {
  const map: Record<string, string | undefined> = { 'Active': 'success', 'Inactive': 'warning', 'Blacklisted': 'danger', '1': 'success', '2': 'warning', '3': 'danger' }
  return map[String(status)]
}

const getCreditRatingText = (rating: string | number) => {
  if (rating === undefined || rating === null || rating === '') return '未设置'
  const map: Record<string, string> = { 'A': 'A级', 'B': 'B级', 'C': 'C级', 'D': 'D级' }
  return map[String(rating)] || '未设置'
}

const getCreditRatingTagType = (rating: string | number) => {
  const map: Record<string, string | undefined> = { 'A': 'success', 'B': 'warning', 'C': 'danger', 'D': 'info' }
  return map[String(rating)]
}

const formatCurrency = (amount: number) => {
  if (!amount && amount !== 0) return '0.00'
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(Number(amount))
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '未设置'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadCustomerList()
})
</script>

<style scoped>
.customer-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.debug-info {
  background: #f0f9ff;
  border: 1px solid #0ea5e9;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 8px;
  font-size: 14px;
}

.debug-header {
  color: #0369a1;
  font-weight: bold;
  margin-bottom: 10px;
}

.error-message {
  color: #dc2626;
  margin-top: 5px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.right-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-management {
    padding: 10px;
  }
  
  .action-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .left-actions,
  .right-actions {
    justify-content: center;
  }
  
  .right-actions .el-input {
    width: 100% !important;
  }
}
</style> 